//
//  UserAccountViewModel.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/18.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    
    //单例
    static let sharedAccountViewModel: UserAccountViewModel = UserAccountViewModel()
    
    
    //定义用户账户模型属性
    var userAccount: UserAccount?
    
    //构造函数私有化  外界不能直接访问
    private override init() {
        super.init()
        userAccount = UserAccount.loadUserAccount()
    }
    
    //用户是否登录
    var userLogin: Bool {
        
        //只读属性
        return userAccount?.access_token != nil
    }
    
    //计算当前登录用户的 token
    var access_token: String? {
        return userAccount?.access_token
    }
    
    //用户名称的只读属性
    var userName: String? {
        return userAccount?.name
    }
    
    //用户头像的url
    var headImageURL: NSURL? {
        
        if let urlString = userAccount?.avatar_large {
            return NSURL(string: urlString)
        }
        return nil
    }
    
    //加载用户的 token
    func loadAccessToken(code: String,finished:(isSuccess: Bool) -> ()) {
        
        //使用AFN发起post的http请求
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        
        HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                
                //执行失败的回调
                finished(isSuccess: false)
                return
            }
            
            //程序走到这里  就一定转换为了字典类型数据
            let userAccount = UserAccount(dict: dict!)
            
            //获取用户信息 发起网络请求
            self.loadUserInfo( userAccount, finished: finished)
        }
        
        
        //        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        //
        //            guard let dict = result as? [String: AnyObject] else {
        //
        //                //数据类型不匹配  默认访问出错
        //                finished(isSuccess: false)
        //                return
        //            }
        //
        //            let userAccount = UserAccount(dict: dict)
        //
        //            //获取用户信息  发起网络请求
        //            self.loadUserInfo(userAccount, finished: finished)
        //            }) { (_, error) -> Void in
        //                finished(isSuccess: false)
        //                print(error)
        //        }
    }
    
    //请求用户信息
    private func loadUserInfo(userAccount:UserAccount,finished:(isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":userAccount.access_token!,"uid":userAccount.uid!]
        
        
        HTTPClient.sharedClient.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            let name = dict!["name"] as! String
            let avatar_large = dict!["avatar_large"] as! String
            
            //完整模型数据
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            //使用完整的对象  调用归档的方法
            userAccount.saveAccount()
            
            //需要给单例对象的 用户模型 赋值
            self.userAccount = userAccount
            
            //用户信息保存完毕之后,执行成功的回调
            finished(isSuccess: true)
        }
        
        
        
        
        //        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        //
        //            print(result)
        //
        //            guard let dict = result as? [String: AnyObject] else {
        //                return
        //            }
        //
        //            let name = dict["name"] as! String
        //            let avatar_large = dict["avatar_large"] as! String
        //
        //            //完整模型数据
        //            userAccount.name = name
        //            userAccount.avatar_large = avatar_large
        //
        //            //使用完整的对象  调用归档的方法
        //            userAccount.saveAccount()
        //
        //            //需要给单例对象的 用户模型 赋值
        //            self.userAccount = userAccount
        //            
        //            //用户信息保存完毕之后,执行成功的回调
        //            finished(isSuccess: true)
        //
        //            }) { (_, error) -> Void in
        //                finished(isSuccess: false)
        //                print(error)
        //        }
        
    }
    
    
}
